package Servidor;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import java.security.Security;
import java.util.ArrayList;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
  
import org.apache.commons.mail.EmailException;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

/**
 *
 * @author Douglas
 */
public class Servidor{
    private static Servidor server = new Servidor();
    private ServerSocket welcome;    
    private ArrayList<User> usuarios; // Lista de todos os usuarios
    private File logins;

    
    private Servidor(){
        try {
            welcome = new ServerSocket(6666);
        } catch (IOException ex) {
            Logger.getLogger(Servidor.class.getName()).log(Level.SEVERE, null, ex);
        }
    usuarios = new ArrayList<>();
    new File("Logins").mkdirs();
    new File("FTP" + File.separator + "arquivos").mkdirs();
    new File("FTP" + File.separator + "users").mkdirs();
    logins = new File("Logins" + File.separator + "Logins.txt");
    System.out.println("ARQUIVO EXISTE>>"+logins.exists());
    CarregaLogins();
    //welcome.setReuseAddress(true);
    
}
    
    public static Servidor getServer(){
        return server;
    }
    
    private void CarregaLogins() {//carrega os logins de um arquivo e instância os usuarios
        
        if(logins.exists()){
            BufferedReader lerFile;
            try {
                lerFile = new BufferedReader(new InputStreamReader(new FileInputStream(logins)));

            while(true){
                String temp = lerFile.readLine();
                if(temp==null) break;
                usuarios.add(new User(temp.split(":")[0], temp.split(":")[1] ));


            }}catch (FileNotFoundException ex) {

            } catch (IOException ex) {
                Logger.getLogger(Servidor.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else
            System.out.println("ARQUIVO NÃO EXISTE");
        
    }
    
    public void SalvaLogins(User user) throws FileNotFoundException, IOException{//salva o login de um novo usuário na lista
        
            System.out.println("EXISTE>>"+logins.exists());
        
            BufferedWriter escreveFile = new BufferedWriter (new FileWriter(logins, true));
            escreveFile.append(user.getLogin()+":"+user.getSenha());
            escreveFile.newLine();
            escreveFile.close();
        
            System.out.println("EXISTE>>"+logins.exists());
    }
    
    
    public void conexao() throws IOException {
        Socket conexao;
        while(true){
        
        conexao = welcome.accept();
        if(conexao!=null)
        new ThreadAtendeCli(conexao, usuarios).start();
        
        }
        
    }
    
    public boolean consultarUsuario(String login) {
        for (int i = 0; i < usuarios.size(); i++) {
            if (login.equals(usuarios.get(i).getLogin())) {
                return true;
            }
        }
        return false;
    }
    
    public User consultarUsuario(String login, String senha) {
        for (int i = 0; i < usuarios.size(); i++) {
            if (login.equals(usuarios.get(i).getLogin()) && senha.equals(usuarios.get(i).getSenha())) {
                return usuarios.get(i);
            }
        }
        return null;
    }
    
    public static void SendEmail(String subject, String body, String recipients) throws EmailException, MessagingException{
      
        String sender = "CloudFlying";
        String mailhost = "smtp.gmail.com";
        
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
		 
        
		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", "smtp");
		props.put("mail.smtp.host", mailhost);
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", "587");
		props.put("mail.smtp.socketFactory.port", "587");
		props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.socketFactory.fallback", "true");
		props.put("mail.smtp.quitwait", "false");
                    props.put("mail.smtp.user", "douglas.ecomp12@gmail.com");
                    props.put("mail.smtp.starttls.enable","true");
                    props.put("mail.smtp.debug", "true");
               

 
		Session session = Session.getDefaultInstance(props,
				new javax.mail.Authenticator() 
		{
                        @Override
                        protected javax.mail.PasswordAuthentication getPasswordAuthentication(){
			 return new javax.mail.PasswordAuthentication("cloudflying00@gmail.com","cloud1234");	
                        }
		});		
 
		MimeMessage message = new MimeMessage(session);
		message.setSender(new InternetAddress(sender));
		message.setSubject(subject);
		message.setContent(body, "text/plain");
		if (recipients.indexOf(',') > 0) 
					message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
		else
					message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
 
	
		Transport.send(message);
    }
    
    public void useFTP(String ftpserver, String directoryName, String nameFiletoUpload, 
        String dirFiletoUpload, String username, String password) {  
        FTPClient ftpClient = new FTPClient();  
  
        try {  
            ftpClient.connect(ftpserver);  
            System.out.print(ftpClient.getReplyString());  
  
            // check reply code.  
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {  
                ftpClient.disconnect();  
                System.out.println("Connection refused.");  
                return;  
            }  
  
            ftpClient.login(username, password);  
            System.out.println("Workdir >>" +  
                ftpClient.printWorkingDirectory());  
            ftpClient.changeWorkingDirectory(directoryName);  
  
            //Store file start  
            FileInputStream inp = new FileInputStream(dirFiletoUpload);  
            BufferedInputStream input = new BufferedInputStream(inp);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.storeFile(nameFiletoUpload, input);  
            //Store file end  
              
            //List all Files and directories  
            FTPFile[] files = ftpClient.listFiles();  
  
            if (files != null) {  
                for (int i = 0; i < files.length; i++) {  
                    //If file print name and size  
                    if (files[i].isFile()) {  
                        System.out.println("File >> " + files[i].getName() +  
                            "   Size >>" + files[i].getSize());  
                    }  
                }  
            }  
            System.out.println("getStatus "+ftpClient.getStatus("/www"));  
            System.out.println("getSystemName "+ftpClient.getSystemName());  
            System.out.println("listHelp "+ftpClient.listHelp());  
            System.out.println("listNames "+ftpClient.listNames());  
            ftpClient.logout();  
            ftpClient.disconnect();  
        } catch (IOException e) {  
            if (ftpClient.isConnected()) {  
                try {  
                    ftpClient.disconnect();  
                } catch (IOException f) {  
                    // do nothing  
                }  
            }  
  
            e.printStackTrace();  
        }  
    }
    
    public static String[] listarArquivos(String username) {
        File file = new File("FTP" + File.separator + username);
        return file.list();
    }
    
        /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException, EmailException, MessagingException {
        Servidor.getServer().conexao();
       // Servidor.getServer().server.useFTP("192.168.0.114", "\\", "The.Walking.Dead.S03E15.rmvb" ,"D:\\douglas\\videos\\BaixandoFacil.com_The.Walking.Dead.S03E15.rmvb"/*"Notadeesclarecimento.docx" "GUJ - Properties.pdf"*/, "Douglas", "0000");
        //Servidor.getServer().server.SendEmail("test", "test", "douglas.ecomp12@gmail.com", "douglas.ecomp12@gmail.com");
       
    }
    
}
